package com.zz.chenko.common.utils;

import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * 缓存工具类
 *
 * @author Zhong
 * @since 2017年1月7日
 */
public class CacheUtil {

    private static Logger logger = LoggerFactory.getLogger(Cache.class);

    private static CacheManager cacheManager = ((EhCacheManager) SpringContextHolder.getBean("cacheManager"))
            .getCacheManager();

    static {
        if (cacheManager == null) {
            EhCacheManager ehCacheManager = SpringContextHolder.getBean("cacheManager");
            ehCacheManager.init();
            cacheManager = ehCacheManager.getCacheManager();
        }
    }

    public static Object get(String cacheName, String key) {
        Element element = getCache(cacheName).get(key);
        return element == null ? null : element.getObjectValue();
    }

    public static void put(String cacheName, String key, Object value) {
        Element element = new Element(key, value);
        getCache(cacheName).put(element);
    }

    public static void remove(String cacheName, String key) {
        getCache(cacheName).remove(key);
    }

    /**
     * 获得一个Cache，没有则创建一个。
     */
    private synchronized static Cache getCache(String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            cacheManager.addCache(cacheName);
            cache = cacheManager.getCache(cacheName);
            cache.getCacheConfiguration().setEternal(false);
        }
        return cache;
    }
}
